const express = require('express');
const validate = require('../../middleware/validate');
const auth = require('../../middleware/auth').auth;
const nutritionValidation = require('../../validators/nutrition.validator');
const nutritionController = require('../../controllers/nutrition.controller');
const mongoose = require('mongoose');

const router = express.Router();

/**
 * @swagger
 * tags:
 *   name: Nutrition
 *   description: 营养分析相关接口
 */

// 营养目标路由
router
  .route('/goals')
  /**
   * @swagger
   * /v1/nutrition/goals:
   *   post:
   *     summary: 创建当前用户的营养目标
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - caloriesGoal
   *               - nutritionGoals
   *               - macroRatio
   *             properties:
   *               caloriesGoal:
   *                 type: number
   *                 description: 卡路里目标
   *               nutritionGoals:
   *                 type: object
   *                 properties:
   *                   protein:
   *                     type: number
   *                     description: 蛋白质目标(g)
   *                   fat:
   *                     type: number
   *                     description: 脂肪目标(g)
   *                   carbohydrate:
   *                     type: number
   *                     description: 碳水化合物目标(g)
   *                   fiber:
   *                     type: number
   *                     description: 膳食纤维目标(g)
   *                   sugar:
   *                     type: number
   *                     description: 糖目标(g)
   *                   sodium:
   *                     type: number
   *                     description: 钠目标(mg)
   *               macroRatio:
   *                 type: object
   *                 properties:
   *                   protein:
   *                     type: number
   *                     description: 蛋白质比例(%)
   *                   fat:
   *                     type: number
   *                     description: 脂肪比例(%)
   *                   carbohydrate:
   *                     type: number
   *                     description: 碳水化合物比例(%)
   *     responses:
   *       "201":
   *         description: 创建成功
   *       "400":
   *         description: 参数错误或用户已有营养目标
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .post(
    auth(),
    (req, res, next) => {
      // 在验证前设置userId
      console.log('设置用户ID中间件执行，用户ID:', req.user.id);
      req.body.userId = req.user.id; 
      next();
    },
    validate(nutritionValidation.createNutritionGoal),
    nutritionController.createNutritionGoal
  )
  /**
   * @swagger
   * /v1/nutrition/goals:
   *   get:
   *     summary: 获取当前用户的营养目标
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   *       "404":
   *         description: 未找到用户营养目标
   */
  .get(
    auth(),
    (req, res, next) => {
      req.params.userId = req.user.id;
      next();
    },
    nutritionController.getNutritionGoal
  )
  /**
   * @swagger
   * /v1/nutrition/goals:
   *   put:
   *     summary: 更新当前用户的营养目标
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             properties:
   *               caloriesGoal:
   *                 type: number
   *                 description: 卡路里目标
   *               nutritionGoals:
   *                 type: object
   *                 properties:
   *                   protein:
   *                     type: number
   *                     description: 蛋白质目标(g)
   *                   fat:
   *                     type: number
   *                     description: 脂肪目标(g)
   *                   carbohydrate:
   *                     type: number
   *                     description: 碳水化合物目标(g)
   *                   fiber:
   *                     type: number
   *                     description: 膳食纤维目标(g)
   *                   sugar:
   *                     type: number
   *                     description: 糖目标(g)
   *                   sodium:
   *                     type: number
   *                     description: 钠目标(mg)
   *               macroRatio:
   *                 type: object
   *                 properties:
   *                   protein:
   *                     type: number
   *                     description: 蛋白质比例(%)
   *                   fat:
   *                     type: number
   *                     description: 脂肪比例(%)
   *                   carbohydrate:
   *                     type: number
   *                     description: 碳水化合物比例(%)
   *     responses:
   *       "200":
   *         description: 更新成功
   *       "400":
   *         description: 参数错误
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   *       "404":
   *         description: 未找到用户营养目标
   */
  .put(
    auth(),
    (req, res, next) => {
      req.params.userId = req.user.id;
      next();
    },
    validate(nutritionValidation.updateNutritionGoal),
    nutritionController.updateNutritionGoal
  )
  /**
   * @swagger
   * /v1/nutrition/goals:
   *   delete:
   *     summary: 删除当前用户的营养目标
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     responses:
   *       "200":
   *         description: 删除成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   *       "404":
   *         description: 未找到用户营养目标
   */
  .delete(
    auth(),
    (req, res, next) => {
      req.params.userId = req.user.id;
      next();
    },
    nutritionController.deleteNutritionGoal
  );

// 营养建议路由
router
  .route('/suggestions')
  /**
   * @swagger
   * /v1/nutrition/suggestions:
   *   get:
   *     summary: 获取当前用户的营养建议列表
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: query
   *         name: type
   *         schema:
   *           type: string
   *           enum: [营养均衡, 热量控制, 蛋白质补充, 碳水适当, 脂肪控制, 膳食纤维, 维生素补充, 钠摄入控制, 其他]
   *         description: 建议类型
   *       - in: query
   *         name: isRead
   *         schema:
   *           type: boolean
   *         description: 是否已读
   *       - in: query
   *         name: startDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 开始日期
   *       - in: query
   *         name: endDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 结束日期
   *       - in: query
   *         name: sortBy
   *         schema:
   *           type: string
   *         description: 排序方式 (例如 createdAt:desc)
   *       - in: query
   *         name: limit
   *         schema:
   *           type: integer
   *           minimum: 1
   *         default: 10
   *         description: 每页数量
   *       - in: query
   *         name: page
   *         schema:
   *           type: integer
   *           minimum: 1
   *         default: 1
   *         description: 页码
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    (req, res, next) => {
      req.query.userId = req.user.id;
      next();
    },
    validate(nutritionValidation.getNutritionSuggestions),
    nutritionController.getNutritionSuggestions
  );

// 修复营养建议路由（返回UI所需的完整建议数据）
// 注意：必须放在/suggestions/:id路由之前
router
  .route('/suggestions/ui')
  /**
   * @swagger
   * /v1/nutrition/suggestions/ui:
   *   get:
   *     summary: 获取用户的营养建议（格式化的UI友好版本）
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    (req, res, next) => {
      console.log('[DEBUG] /suggestions/ui 中间件1：auth() 后');
      console.log('[DEBUG] req.user:', req.user);
      req.query.userId = req.user.id;
      console.log('[DEBUG] 设置 req.query.userId 后:', req.query);
      next();
    },
    (req, res, next) => {
      console.log('[DEBUG] /suggestions/ui 中间件3：直接进入控制器前');
      console.log('[DEBUG] req.params:', req.params);
      console.log('[DEBUG] req.query:', req.query);
      // 直接修改请求的参数对象，以满足控制器期望
      // 确保userId是一个有效的MongoDB ObjectId
      if (req.query.userId && mongoose.Types.ObjectId.isValid(req.query.userId)) {
        console.log('[DEBUG] userId有效，继续处理');
      } else {
        console.log('[DEBUG] 无效的userId，尝试使用req.user.id');
        req.query.userId = req.user.id;
      }
      next();
    },
    nutritionController.generateNutritionSuggestions
  );

// 标记所有建议为已读 - 必须放在/:id路由前面
router
  .route('/suggestions/read-all')
  /**
   * @swagger
   * /v1/nutrition/suggestions/read-all:
   *   post:
   *     summary: 标记当前用户所有营养建议为已读
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     responses:
   *       "200":
   *         description: 操作成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .post(
    auth(),
    (req, res, next) => {
      req.params.userId = req.user.id;
      next();
    },
    nutritionController.markAllSuggestionsAsRead
  );

// 单条营养建议路由 - 需要放在/ui和/read-all路由后面
router
  .route('/suggestions/:id')
  /**
   * @swagger
   * /v1/nutrition/suggestions/{id}:
   *   get:
   *     summary: 获取单条营养建议详情
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: string
   *         description: 营养建议ID
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   *       "404":
   *         description: 未找到营养建议
   */
  .get(
    auth(),
    validate(nutritionValidation.getNutritionSuggestion),
    nutritionController.getNutritionSuggestion
  )
  /**
   * @swagger
   * /v1/nutrition/suggestions/{id}:
   *   put:
   *     summary: 更新营养建议状态（仅允许更新已读状态）
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: string
   *         description: 营养建议ID
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - isRead
   *             properties:
   *               isRead:
   *                 type: boolean
   *                 description: 是否已读
   *     responses:
   *       "200":
   *         description: 更新成功
   *       "400":
   *         description: 参数错误
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   *       "403":
   *         description: 无权限修改
   *       "404":
   *         description: 未找到营养建议
   */
  .put(
    auth(),
    (req, res, next) => {
      // 用户只能更新isRead字段
      if (Object.keys(req.body).some(key => key !== 'isRead')) {
        return res.status(403).send({
          error: 403,
          message: '用户只能更新营养建议的已读状态',
        });
      }
      next();
    },
    validate(nutritionValidation.updateNutritionSuggestion),
    nutritionController.updateNutritionSuggestion
  );

// 营养分析路由
router
  .route('/analysis')
  /**
   * @swagger
   * /v1/nutrition/analysis:
   *   get:
   *     summary: 获取当前用户的营养分析数据
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: query
   *         name: startDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 开始日期 (不提供则根据period自动计算)
   *       - in: query
   *         name: endDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 结束日期 (不提供则使用今天)
   *       - in: query
   *         name: period
   *         schema:
   *           type: string
   *           enum: [day, week, month]
   *         default: week
   *         description: 分析周期
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "400":
   *         description: 参数错误
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    (req, res, next) => {
      req.query.userId = req.user.id;
      next();
    },
    validate(nutritionValidation.getNutritionAnalysis),
    nutritionController.getNutritionAnalysis
  );

// 营养分析路由
router
  .route('/analysis/calories')
  /**
   * @swagger
   * /v1/nutrition/analysis/calories:
   *   get:
   *     summary: 获取用户热量摄入趋势数据
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: query
   *         name: period
   *         schema:
   *           type: string
   *           enum: [7, 30, 90]
   *         default: 7
   *         description: 时间段（7天、30天、90天）
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    validate(nutritionValidation.getCaloriesTrend),
    nutritionController.getCaloriesTrend
  );

router
  .route('/analysis/ratio')
  /**
   * @swagger
   * /v1/nutrition/analysis/ratio:
   *   get:
   *     summary: 获取用户营养素比例数据
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: query
   *         name: period
   *         schema:
   *           type: string
   *           enum: [today, week, month]
   *         default: today
   *         description: 时间段（今天、本周、本月）
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    validate(nutritionValidation.getNutrientRatio),
    nutritionController.getNutrientRatio
  );

router
  .route('/analysis/details')
  /**
   * @swagger
   * /v1/nutrition/analysis/details:
   *   get:
   *     summary: 获取用户营养素详细数据
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     parameters:
   *       - in: query
   *         name: period
   *         schema:
   *           type: string
   *           enum: [today, week, month]
   *         default: today
   *         description: 时间段（今天、本周、本月）
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    validate(nutritionValidation.getNutrientDetails),
    nutritionController.getNutrientDetails
  );

// 修复营养建议路由（返回UI所需的完整建议数据）
router
  .route('/suggestions/ui')
  /**
   * @swagger
   * /v1/nutrition/suggestions/ui:
   *   get:
   *     summary: 获取用户的营养建议（格式化的UI友好版本）
   *     tags: [Nutrition]
   *     security:
   *       - bearerAuth: []
   *     responses:
   *       "200":
   *         description: 获取成功
   *       "401":
   *         $ref: '#/components/responses/Unauthorized'
   */
  .get(
    auth(),
    (req, res, next) => {
      console.log('[DEBUG] /suggestions/ui 中间件1：auth() 后');
      console.log('[DEBUG] req.user:', req.user);
      req.query.userId = req.user.id;
      console.log('[DEBUG] 设置 req.query.userId 后:', req.query);
      next();
    },
    (req, res, next) => {
      console.log('[DEBUG] /suggestions/ui 中间件3：直接进入控制器前');
      console.log('[DEBUG] req.params:', req.params);
      console.log('[DEBUG] req.query:', req.query);
      // 直接修改请求的参数对象，以满足控制器期望
      // 确保userId是一个有效的MongoDB ObjectId
      if (req.query.userId && mongoose.Types.ObjectId.isValid(req.query.userId)) {
        console.log('[DEBUG] userId有效，继续处理');
      } else {
        console.log('[DEBUG] 无效的userId，尝试使用req.user.id');
        req.query.userId = req.user.id;
      }
      next();
    },
    nutritionController.generateNutritionSuggestions
  );

// 添加全新的路由路径，避免任何冲突
router
  .route('/ui-suggestions')
  .get(
    auth(),
    (req, res) => {
      try {
        console.log('[DEBUG] /ui-suggestions 路由被访问');
        
        // 直接从req.user中获取userId
        const userId = req.user.id;
        console.log('[DEBUG] 用户ID:', userId);
        
        if (!userId || !mongoose.Types.ObjectId.isValid(userId)) {
          console.log('[DEBUG] 无效的用户ID');
          return res.status(400).json({
            error: 1,
            body: null,
            message: '有效的用户ID是必需的',
            code: 400
          });
        }
        
        // 手动生成一些建议数据（与generateNutritionSuggestions控制器中相同）
        const suggestions = [
          {
            type: 'protein',
            icon: 'protein_icon',
            title: '增加蛋白质摄入',
            content: '建议增加瘦肉、水果和谷物的摄入，提高蛋白质供给量。',
            color: '#E1F5FE',
            isRead: false
          },
          {
            type: 'water',
            icon: 'water_icon',
            title: '增加水分摄入',
            content: '每日饮水量建议达到2000ml以上，保持身体充分水合。',
            color: '#E3F2FD',
            isRead: false
          },
          {
            type: 'protein_source',
            icon: 'protein_source_icon',
            title: '优化蛋白质来源',
            content: '建议增加瘦肉、鱼类和豆制品摄入，减少红肉和加工肉制品摄入。',
            color: '#FFF3E0',
            isRead: false
          },
          {
            type: 'sodium',
            icon: 'sodium_icon',
            title: '注意钠盐摄入',
            content: '建议减少调味料和加工食品的摄入，适量增加水果摄量。',
            color: '#FFEBEE',
            isRead: false
          }
        ];
        
        console.log('[DEBUG] 返回建议数量:', suggestions.length);
        
        // 直接返回响应
        return res.json({
          error: 0,
          body: { suggestions },
          message: '获取营养建议成功'
        });
      } catch (error) {
        console.error('[DEBUG] 错误:', error);
        return res.status(500).json({
          error: 1,
          body: null,
          message: error.message,
          code: 500
        });
      }
    }
  );

// 临时调试路由，用于显示所有路由
router
  .route('/debug-routes')
  .get((req, res) => {
    console.log('请求调试路由');
    const routes = [];
    
    // 获取路由器中的所有路由
    router.stack.forEach((middleware) => {
      if (middleware.route) {
        // 获取路由的路径和方法
        const path = middleware.route.path;
        const methods = Object.keys(middleware.route.methods).filter(method => middleware.route.methods[method]);
        
        // 获取路由中所有的中间件
        const middlewares = middleware.route.stack.map(handler => {
          return {
            name: handler.name || 'anonymous',
            method: handler.method
          };
        });
        
        routes.push({
          path,
          methods,
          middlewares
        });
      }
    });
    
    res.json({
      error: 0,
      body: {
        routes,
        total: routes.length
      },
      message: '获取路由配置成功'
    });
  });

module.exports = router; 